package global

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"simple-app/structs/tables"
	"time"
)

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		&tables.Address{},
		&tables.Bank{},
		&tables.OptionLog{},
		&tables.Product{},
		&tables.ProductOrder{},
		&tables.Resale{},
		&tables.ResaleOrder{},
		&tables.Setting{},
		&tables.User{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				logrus.Errorf("初始化数据库表结构异常: %v", err)
			}
		}
	}
	initUser()
	initSetting()
}

func initUser() {
	var err error
	var rootUser = &tables.User{
		UserId:            tables.RootId,
		Account:           "root",
		Password:          "3.14",
		Status:            tables.UserStatusActivated,
		AccountLv:         tables.AccountLvForRoot,
		Nickname:          "超级管理员",
		Phone:             "10086",
		ReferrerId:        0,
		TokenMoney:        0,
		Score:             0,
		RoleCode:          "sys",
		InviteCode:        "8888",
		ResidueAuctionNum: 9999,
		PrivilegeEndTime:  0,
		PrivilegeNum:      9999,
		CreatedAt:         time.Now().Unix(),
		DeletedAt:         0,
	}
	var d tables.User
	if err = DB.Where("user_id = 1").First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = DB.Create(rootUser).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化用户信息时发生错误：%v", err))
		}
		rootAddress := tables.Bank{
			Id:          1,
			UserId:      1,
			AccountType: 1,
			AccountDesc: "公司默认收款账户",
			AccountNum:  "test11111",
			IsDefault:   1,
			CreatedAt:   time.Now().Unix(),
			UpdatedAt:   0,
		}
		if DB.Create(&rootAddress).Error != nil {
			panic(fmt.Sprintf("导入初始化用户信息时发生错误：%v", err))
		}

	}
}

func initSetting() {
	var err error
	m := tables.Setting{
		Id:                  1,
		PremiumPre:          0.03,
		ServiceMoneyPre:     0.015,
		AuctionNumForDay:    2,
		PriorityDay:         3,
		PriorityNum:         2,
		ReferrerPriorityDay: 2,
		PriorityMinute:      1,
	}
	var d tables.Setting
	if err = DB.Where("id = 1").First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = DB.Create(&m).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化配置信息时发生错误：%v", err))
		}
	}
}
